package com.example.calendar.ui.components.tasks

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccessTime
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.Flag
import androidx.compose.material.icons.filled.Notifications
import androidx.compose.material.icons.outlined.RadioButtonUnchecked
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.calendar.data.model.Task
import com.example.calendar.data.model.TaskPriority
import com.example.calendar.ui.theme.categoryDefault
import com.example.calendar.ui.theme.priorityHigh
import com.example.calendar.ui.theme.priorityLow
import com.example.calendar.ui.theme.priorityMedium
import com.example.calendar.util.DateTimeUtils
import org.threeten.bp.LocalDateTime

/**
 * A composable that displays a task item.
 */
@Composable
fun TaskItem(
    task: Task,
    onClick: () -> Unit,
    onToggleCompleted: () -> Unit,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
            .clickable(onClick = onClick),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(8.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // Category color indicator
            Box(
                modifier = Modifier
                    .size(16.dp)
                    .clip(CircleShape)
                    .background(Color(task.color ?: categoryDefault.value.toInt()))
            )
            
            Spacer(modifier = Modifier.width(12.dp))
            
            // Task details
            Column(
                modifier = Modifier.weight(1f)
            ) {
                // Title
                Text(
                    text = task.title,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.SemiBold,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    textDecoration = if (task.isCompleted) TextDecoration.LineThrough else TextDecoration.None,
                    color = if (task.isCompleted) MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f) else MaterialTheme.colorScheme.onSurface
                )
                
                Spacer(modifier = Modifier.height(4.dp))
                
                // Due date
                task.dueDate?.let {
                    TaskDetailRow(
                        icon = Icons.Default.AccessTime,
                        text = DateTimeUtils.formatDateTime(it),
                        tint = if (task.isOverdue() && !task.isCompleted) priorityHigh else MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                
                // Priority
                TaskDetailRow(
                    icon = Icons.Default.Flag,
                    text = when (task.priority) {
                        TaskPriority.HIGH -> "High priority"
                        TaskPriority.MEDIUM -> "Medium priority"
                        TaskPriority.LOW -> "Low priority"
                        else -> "Medium priority"
                    },
                    tint = when (task.priority) {
                        TaskPriority.HIGH -> priorityHigh
                        TaskPriority.MEDIUM -> priorityMedium
                        TaskPriority.LOW -> priorityLow
                        else -> priorityMedium
                    }
                )
                
                // Reminder indicator (if has reminders)
                if (task.reminderMinutes.isNotEmpty()) {
                    Spacer(modifier = Modifier.height(2.dp))
                    TaskDetailRow(
                        icon = Icons.Default.Notifications,
                        text = "${task.reminderMinutes.first()} minutes before"
                    )
                }
            }
            
            // Completion toggle
            IconButton(
                onClick = onToggleCompleted,
                modifier = Modifier.size(36.dp)
            ) {
                Icon(
                    imageVector = if (task.isCompleted) Icons.Default.CheckCircle else Icons.Outlined.RadioButtonUnchecked,
                    contentDescription = if (task.isCompleted) "Mark as incomplete" else "Mark as complete",
                    tint = if (task.isCompleted) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

@Composable
fun TaskDetailRow(
    icon: ImageVector,
    text: String,
    tint: Color = MaterialTheme.colorScheme.onSurfaceVariant
) {
    Row(
        verticalAlignment = Alignment.CenterVertically
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            modifier = Modifier.size(16.dp),
            tint = tint
        )
        
        Spacer(modifier = Modifier.width(4.dp))
        
        Text(
            text = text,
            style = MaterialTheme.typography.bodySmall,
            color = tint,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

@Preview(showBackground = true)
@Composable
fun TaskItemPreview() {
    val sampleTask = Task(
        id = "1",
        title = "Complete project report",
        description = "Finish the quarterly project report",
        dueDate = LocalDateTime.now().plusDays(1),
        isCompleted = false,
        priority = TaskPriority.HIGH,
        reminderMinutes = listOf(30),
        color = categoryDefault.value.toInt()
    )
    
    MaterialTheme {
        TaskItem(
            task = sampleTask,
            onClick = {},
            onToggleCompleted = {},
            modifier = Modifier.padding(16.dp)
        )
    }
}

@Preview(showBackground = true)
@Composable
fun CompletedTaskItemPreview() {
    val sampleTask = Task(
        id = "2",
        title = "Review documentation",
        description = "Review project documentation",
        dueDate = LocalDateTime.now().minusDays(1),
        isCompleted = true,
        completedDate = LocalDateTime.now(),
        priority = TaskPriority.MEDIUM,
        color = categoryDefault.value.toInt()
    )
    
    MaterialTheme {
        TaskItem(
            task = sampleTask,
            onClick = {},
            onToggleCompleted = {},
            modifier = Modifier.padding(16.dp)
        )
    }
} 